package com.joey.concurrency.example.count;

import com.joey.concurrency.annotation.ThreadSafe;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author hyy
 **/
@ThreadSafe
public class AtomicBooleanSafeExample implements Runnable{

    private AtomicBoolean someone = new AtomicBoolean(false);

    @Override
    public void run() {
        if (someone.compareAndSet(false,true)) {
            System.out.println(Thread.currentThread().getName()+": after judgment,the some is "+someone);
            try {
                Thread.sleep(1000);
                someone.set(true);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" i am coming");
            System.out.println(Thread.currentThread().getName()+" i have to leaving");
            someone.set(false);
        }else{
            System.out.println(Thread.currentThread().getName()+" i can't visit the house!");
        }
    }

    public static void main(String[] args) {
        AtomicBooleanSafeExample obj = new AtomicBooleanSafeExample();
        new Thread(obj,"Thread1").start();
        new Thread(obj,"Thread2").start();
        new Thread(obj,"Thread3").start();
    }
}
